package Tools.JUCTools;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

import static ProcessThread.util.Sleeper.sleep;


@Slf4j(topic = "c.TestCyclicBarrier")
public class TestCyclicBarrier {

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(2);
        CyclicBarrier barrier = new CyclicBarrier(2, ()-> {
            log.debug("task1, task2 finish...");
        });
        for (int i = 0; i < 3; i++) { // task1  task2  task1
            int j = i;
            service.submit(() -> {
                log.debug("task1 begin{}...",j);
                sleep(1);
                try {
                    System.out.println(barrier.getNumberWaiting());
                    barrier.await(); // 2-1=1

                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
            service.submit(() -> {
                log.debug("task2 begin{}...",j);
                sleep(2);
                try {
                    System.out.println(barrier.getNumberWaiting());
                    barrier.await(); // 1-1=0

                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }

    }


}
